package com.adrian.misc.fractal;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileFilter;

public class FractalFrame extends JFrame implements ActionListener, ItemListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JMenuBar mb = new JMenuBar();
	JMenu fileMenu = new JMenu("File");
	JMenu viewMenu = new JMenu("View");
	JMenuItem saveMenu = new JMenuItem("Save");
	JRadioButtonMenuItem expandMenu = new JRadioButtonMenuItem("Expand View to screen Ratio");
	JRadioButtonMenuItem stretchMenu = new JRadioButtonMenuItem("Stretch to Screen Ratio");
	JRadioButtonMenuItem maintainMenu = new JRadioButtonMenuItem("Maintain ratio");
	ButtonGroup bg = new ButtonGroup();
	JCheckBoxMenuItem fullScreen = new JCheckBoxMenuItem("Fullscreen");
	
	FractalCanvas mCan;
	GraphicsDevice gd;
	public FractalFrame(Fractal fractal) throws HeadlessException {
		this("Fraxplorer", fractal);
	}


	public FractalFrame(String name, Fractal fractal ) throws HeadlessException {
		super(name);
		gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
		maintainMenu.setSelected(true);
		expandMenu.setActionCommand("expand");
		stretchMenu.setActionCommand("stretch");
		maintainMenu.setActionCommand("maintain");
		bg.add(expandMenu);bg.add(stretchMenu);bg.add(maintainMenu);
		saveMenu.addActionListener(this);
		expandMenu.addActionListener(this);
		stretchMenu.addActionListener(this);
		maintainMenu.addActionListener(this);
		fullScreen.addItemListener(this);
		
		fileMenu.add(saveMenu);
		viewMenu.add(expandMenu);
		viewMenu.add(stretchMenu);
		viewMenu.add(maintainMenu);
		viewMenu.addSeparator();
		viewMenu.add(fullScreen);
		mb.add(fileMenu);
		mb.add(viewMenu);

		new JScrollPane((JComponent) mCan);
		setJMenuBar(mb);
        DisplayMode mode = gd.getDisplayMode();
        setSize(new Dimension(mode.getWidth(), mode.getHeight()-28) );
        mCan = new MandelbrotCanvas(fractal,1024,768,false);
        add(new JScrollPane((Component)mCan));
        mCan.setColorSync(false);
		mCan.setSync(false);
		mCan.repaint();
	}


	public void actionPerformed(ActionEvent actn) {
		if ( "save".equalsIgnoreCase( actn.getActionCommand() ) ) {
			JFileChooser fc = new JFileChooser("desktop");
			fc.setAcceptAllFileFilterUsed(false);
			fc.addChoosableFileFilter(  new FileFilter()
	        {
	            public boolean accept(File f)
	            {
	            	boolean result = false;
	            	if (f.isDirectory()) return true;
	                if (f.getName().toUpperCase().endsWith(".JPG")) result = true;
	                if (f.getName().toUpperCase().endsWith(".JPEG")) result = true;
	                return result;
	            }

	            public String getDescription()
	            {
	                return "JPG (Smaller files but Lossy image compression)";
	            }
	        });


			fc.addChoosableFileFilter(  new FileFilter()
	        {
	            public boolean accept(File f)
	            {
	            	boolean result = false;
	            	if (f.isDirectory()) return true;
	                if (f.getName().toUpperCase().endsWith(".PNG")) result = true;
	                return result;
	            }

	            public String getDescription()
	            {
	                return "PNG (Lossless image compression but larger files)";
	            }
	        });
			int returnVal = fc.showSaveDialog(this);
			 if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File outputfile = fc.getSelectedFile();
	                try {
	                	String name = outputfile.getName();
	                	String type =null;
	                	System.out.println("Description="+ fc.getFileFilter().getDescription());
	        			if (fc.getFileFilter().getDescription().indexOf("JPG") >= 0){
	        				type = "JPG";
	        				if  ( (!outputfile.getAbsolutePath().toUpperCase().endsWith(".JPG")) &&
	        						 (!outputfile.getAbsolutePath().toUpperCase().endsWith(".JPEG")) ){
	        					outputfile = new File(outputfile.getAbsolutePath()+".jpg");
	        				}
	        				System.out.println("TYPE- " + type + "outfile"+outputfile.getAbsolutePath());
	        			} 
	        			else if (fc.getFileFilter().getDescription().indexOf("PNG") >= 0) {
	        				type = "PNG";
	        				if  (!outputfile.getAbsolutePath().toUpperCase().endsWith(".PNG") ){
	        					outputfile = new File(outputfile.getAbsolutePath()+".png");
	        				}
	        				System.out.println("TYPE- " + type + "outfile"+outputfile.getAbsolutePath());
	        			} else {
	        				type = (name.substring(name.indexOf(".")+1)).toUpperCase();
	        				System.out.println("TYPE- " + type + "outfile"+outputfile.getAbsolutePath());
	        			}
	        			 
	                	System.out.println("Writing to - " + outputfile.getAbsolutePath() + ",Type="+ type + "|");
						ImageIO.write(mCan.getImage(),type, outputfile);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
	            } else {
	            
	            }
		}
		if ( "expand".equalsIgnoreCase( actn.getActionCommand() ) ) {
			mCan.setDrawMode(MandelbrotCanvas.MODE_EXPAND_VIEW);
		}
		if ( "stretch".equalsIgnoreCase( actn.getActionCommand() ) ) {
			mCan.setDrawMode(MandelbrotCanvas.MODE_STRETCH);
		}
		if ( "maintain".equalsIgnoreCase( actn.getActionCommand() ) ) {
			mCan.setDrawMode(MandelbrotCanvas.MODE_MAINTAIN_ASPECT);
		}
		
	}


	public void itemStateChanged(ItemEvent e) {
		if (e.getSource() instanceof JCheckBoxMenuItem ) {
			System.out.println(gd.getFullScreenWindow());
			if (gd.getFullScreenWindow()!=null) {
				this.dispose();
				this.setResizable(true);
				this.setUndecorated(false);
				gd.setFullScreenWindow(null);
				this.setVisible(true);
			} else {
				this.dispose();
				this.setResizable(false);
				this.setUndecorated(true);
				gd.setFullScreenWindow(this);
				this.setVisible(true);				
			}
			return;
		}
		
	}

	public void setFractal(Fractal fr) {
		dispose();
		maintainMenu.setSelected(true);
		mCan.setFractal(fr);
		mCan.setColorSync(false);
		mCan.setSync(false);
		mCan.repaint();
		dispose();
	}
}
